package com.bwie.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.mapper.TbDictMapper;
import com.bwie.mapper.TbProdImageMapper;
import com.bwie.poi.StringUtils;
import com.bwie.pojo.TbDict;
import com.bwie.pojo.TbLog;
import com.bwie.pojo.TbProd;
import com.bwie.pojo.TbProdImage;
import com.bwie.service.IUserService;
import com.bwie.service.TbProdService;
import com.bwie.mapper.TbProdMapper;
import com.bwie.utils.R;
import com.bwie.vo.PageInfoVo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
* @author andy
* @description 针对表【tb_prod(商品表)】的数据库操作Service实现
* @createDate 2025-04-23 15:22:59
*/
@Service
public class TbProdServiceImpl extends ServiceImpl<TbProdMapper, TbProd>
    implements TbProdService{

    @Autowired
    TbProdMapper tbProdMapper;

    @Autowired
    TbProdImageMapper tbProdImageMapper;

    @Autowired
    TbDictMapper tbDictMapper;

    @Autowired
    HttpServletRequest request;

    @Autowired
    IUserService iUserService;

    @Autowired
    KafkaTemplate kafkaTemplate;

    @Override
    public R getProdList(PageInfoVo pageInfoVo) {
        //-- 构造分页参数
        Page<TbProd> page = new Page<>(pageInfoVo.getPageNum(), pageInfoVo.getPageSize());

        //-- 获取token，得到userId
        String token = request.getHeader("token");
        if(token == null) {
            return R.ERROR(500, "请先登录");
        }
        Claims body = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
        Integer userId = body.get("userId", Integer.class);

        // 根据userId查询用户的角色
        R r = iUserService.getRoleListByUserId(userId);
        if(r.getCode() != 200) {
            return r;
        }
        String s = JSON.toJSONString(r.getData());
        List<String> roleList = JSON.parseArray(s, String.class);

        Integer adminId = userId;
        if(roleList.contains("管理员")) {
            // 设置null，不进行过滤，就是查询所有的
            adminId = null;
        }


        //-- 分页获取列表
        Page<TbProd> tbProdPage = tbProdMapper.getProdList(page, pageInfoVo.getKeyWord(), adminId);

        //-- 获取商品的图片列表
        for (TbProd record : tbProdPage.getRecords()) {
            List<TbProdImage> list = tbProdImageMapper.selectList(
                    new QueryWrapper<TbProdImage>().lambda().eq(TbProdImage::getProdId, record.getProdId())
            );
            record.setProdImgList(list);
        }

        //-- 购买数量默认设置为1
        for (TbProd record : tbProdPage.getRecords()) {
            record.setBuyNum(1);
        }

        return R.OK(tbProdPage);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R addProd(TbProd tbProd) {

        //-- 获取用户ID
        String token = request.getHeader("token");
        if(token == null) {
            return R.ERROR(500, "请先登录");
        }
        Claims body = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
        Integer userId = body.get("userId", Integer.class);
        System.out.println("userId:" + userId);

        //-- 名称唯一性校验
        TbProd one = tbProdMapper.selectOne(
                new QueryWrapper<TbProd>().lambda().eq(TbProd::getProdName, tbProd.getProdName())
        );
        if(one != null) {
            return R.ERROR(500, "商品名称重复");
        }

        //-- 添加商品
        tbProd.setCreateTime(new Date());
        tbProd.setProdStatus(0);
        tbProd.setUserId(userId);
        tbProdMapper.insert(tbProd);

        //-- 添加商品图片
        if(tbProd.getProdImgList() != null && tbProd.getProdImgList().size() > 0) {
            for (TbProdImage tbProdImage : tbProd.getProdImgList()) {
                tbProdImage.setProdId(tbProd.getProdId());
                tbProdImageMapper.insert(tbProdImage);
            }
        }

        return R.OK();
    }

    @Override
    public R getDictList(Integer typeId) {

        List<TbDict> tbDicts = tbDictMapper.selectList(
                new QueryWrapper<TbDict>().lambda().eq(TbDict::getDictType, typeId)
        );

        return R.OK(tbDicts);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R deleteProd(Integer prodId) {
        //-- 删除商品图片
        tbProdImageMapper.delete(
                new QueryWrapper<TbProdImage>().lambda().eq(TbProdImage::getProdId, prodId)
        );

        //-- 删除商品
        tbProdMapper.deleteById(prodId);


        return R.OK();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R updateProd(TbProd tbProd) {
        //-- 判断商品是否存在
        TbProd prod = tbProdMapper.selectById(tbProd.getProdId());
        if(prod == null) {
            return R.ERROR(404, "商品不存在");
        }

        //-- 更新商品
        tbProdMapper.updateById(tbProd);

        //-- 删除商品的所有图片
        tbProdImageMapper.delete(
                new QueryWrapper<TbProdImage>().lambda().eq(TbProdImage::getProdId, tbProd.getProdId())
        );

        //-- 添加商品图片
        if(tbProd.getProdImgList() != null && tbProd.getProdImgList().size() > 0) {
            for (TbProdImage tbProdImage : tbProd.getProdImgList()) {
                tbProdImage.setProdId(tbProd.getProdId());
                tbProdImageMapper.insert(tbProdImage);
            }
        }

        return R.OK();
    }

    @Override
    public R sendMessage(String msg) {

        System.out.println("Kafaka发送消息:" + msg);
        kafkaTemplate.send("topic-test", msg);

        return R.OK();
    }

    @Override
    public R changeProdStatus(TbProd tbProd) {
        TbLog tbLog = new TbLog();
        tbLog.setCreateTime(new Date());
        tbLog.setLogName("商品审核");
        tbLog.setLogType(6);
        tbLog.setIp(request.getRemoteAddr());

        // 解析token，获取用户信息
        String token = request.getHeader("token");
        if(token == null) {
            return R.ERROR(500, "请先登录");
        }
        Claims body = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
        Integer userId = body.get("userId", Integer.class);
        String nickName = body.get("nickName", String.class);

        tbLog.setOptId(userId);
        tbLog.setOptName(nickName);
        String content = "";

        TbProd prod = tbProdMapper.selectById(tbProd);
        if(prod == null) {
            content = "商品不存在";
            return R.ERROR(404, "商品不存在");
        }

        //-- 审核 == 1
        if(tbProd.getProdStatus() == 1) {
            prod.setProdStatus(tbProd.getProdStatus());
            tbProdMapper.updateById(prod);

            content = "提交审核：" + tbProd.getProdName();
        }

        //-- 上线(审核通过) == 2
        if(tbProd.getProdStatus() == 2) {
            prod.setProdStatus(tbProd.getProdStatus());
            tbProdMapper.updateById(prod);

            // 异步发送短信
            String message = JSON.toJSONString(prod);
            kafkaTemplate.send("topic-prod", message);
            System.out.println("发送Kafka消息：" + message);

            content = "审核通过：" + tbProd.getProdName();
        }

        //-- 驳回 == 3
        if(tbProd.getProdStatus() == 3) {

            if(StringUtils.isEmpty(tbProd.getReason())) {
                return R.ERROR(500, "审核驳回必须填写审核理由");
            }

            prod.setProdStatus(tbProd.getProdStatus());
            prod.setReason(tbProd.getReason());
            tbProdMapper.updateById(prod);

            // 异步发送邮件
            String message = JSON.toJSONString(prod);
            kafkaTemplate.send("topic-prod", message);
            System.out.println("发送Kafka消息：" + message);

            content = "审核驳回：" + tbProd.getProdName();

        }

        //-- 下线 == 4
        if(tbProd.getProdStatus() == 4) {
            prod.setProdStatus(tbProd.getProdStatus());
            tbProdMapper.updateById(prod);

            content = "商品下线：" + tbProd.getProdName();

        }

        // 异步记录操作日志
        tbLog.setLogContent(content);
        kafkaTemplate.send("topic-log", JSON.toJSONString(tbLog));

        return R.OK();
    }

    @KafkaListener(topics = "topic-test")
    public void recvTestMessage(String msg, Acknowledgment acknowledgment) {
        System.out.println("Kafka接收到消息:" + msg);

        // 消息的手动确认（执行后，会把该消息从队列中删除）
        acknowledgment.acknowledge();
    }
}




